import React from 'react'
import {
  DndContext,
  DragEndEvent,
  // KeyboardSensor,
  // PointerSensor,
  closestCenter,
  useSensor,
  useSensors,
  MouseSensor,
} from '@dnd-kit/core'
import {
  SortableContext,
  // arrayMove,
  // sortableKeyboardCoordinates,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable'

type PropsType = {
  children: JSX.Element | JSX.Element[]
  items: Array<{
    id: string
    [key: string]: any
  }>
  onDragEnd: (oldIndex: number, newIndex: number) => void
}

const SortableContainer: React.FC<PropsType> = ({ items, children, onDragEnd }) => {
  const sensors = useSensors(
    // useSensor(PointerSensor),
    useSensor(MouseSensor, {
      activationConstraint: {
        distance: 8, // 8 px
      },
    })
    // useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  )

  function handleDragEnd({ active, over }: DragEndEvent) {
    if (over == null) return
    if (active.id !== over.id) {
      const oldIndex = items.findIndex(c => c.fe_id === active.id)
      const newIndex = items.findIndex(c => c.fe_id === over.id)
      if (onDragEnd) {
        onDragEnd(oldIndex, newIndex)
      }
    }
  }

  return (
    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
      <SortableContext items={items} strategy={verticalListSortingStrategy}>
        {children}
      </SortableContext>
    </DndContext>
  )
}
export default SortableContainer
